// 导入axios
import axios from 'axios'
import Cookies from 'js-cookie'
import jquery from 'jquery'
import rsa from './rsa'
import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'
import {useConfigStore} from '@/stores/config'
import {useLocalConfigStore} from '@/stores/localConfig'
import {collect} from 'collect.js'
const env = import.meta.env



//加密要提交数据
const encryptData = (data_str,server_rsa_pub,app_key)=>{
    const configStore = useConfigStore()
    const key = app_key || configStore.config.app_key;
    const iv = CryptoJS.MD5(Date.now()).toString().slice(0,16);
    //const iv = '025c8c1a9065b789';
    let data = CryptoJS.AES.encrypt(data_str, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    }).toString(); //业务数据加密
    //console.log(data_str,key,data,iv);
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(server_rsa_pub);
    // 使用公钥加密解密向量数据
    let aes_key = encryptor.encrypt(iv);
    let res = {
        aes_key:aes_key,
        data:data
    };
    let sign = CryptoJS.MD5(JSON.stringify(res)+key).toString();
    res.sign = sign;
    return res;
};
//解密后端响应数据
const decryptData = (raw_data,pri_key,app_key)=>{
    if(!raw_data){
        //console.log('解密源数据必填');
        return false;
    }
    let sign = raw_data.sign;
    let data = raw_data.data;
    let aes_key = raw_data.aes_key;
    if(!sign || !data || !aes_key){
        //console.log('解析解密源数据项错误');
        return false;
    }
    const configStore = useConfigStore()
    const key = app_key || configStore.config.app_key;
    if(sign!==CryptoJS.MD5(collect(raw_data).except(['sign']).toJson()+key).toString()){
        //console.log('解析验签失败');
        return false;
    }
    const encryptor = new JSEncrypt();
    encryptor.setPrivateKey(pri_key);
    // 使用公钥加密解密向量数据
    let iv = encryptor.decrypt(aes_key);
    let result = CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return JSON.parse(result.toString(CryptoJS.enc.Utf8));
};
const decryptResponse = (response)=>{
    let headers = response.headers || {};
    let raw_data = response.data;
    //响应加密先对数据进行解密
    if(
        (headers['Response-Encryption']==1) ||
        (   raw_data &&
            typeof raw_data['sign']=='string' &&
            typeof raw_data['data']=='string' &&
            typeof raw_data['aes_key']=='string'
        )
    ){
        const configStore = useConfigStore()
        let app_key = configStore.config.app_key || rsa.app_key;
        let decode_data = decryptData(raw_data,rsa.client_rsa,app_key);
        if(decode_data){
            response.data = decode_data;
        }
    }
    return response;
}

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.withCredentials = true;
//前缀
let prefix = env.VITE_WEB_API_MODEL=='api'?'/api':'/web-api'
// 创建axios实例
const request = axios.create({
    // 基础URL，根据环境不同可以动态配置
    baseURL: (env.VITE_API_BASE_URL || '') + prefix,
})

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        const configStore = useConfigStore()
        // 本地配置信息
        const localConfigStore = useLocalConfigStore()
        //客户端连接信息
        if (configStore.clientId) {
            config.headers['Client-Id'] = configStore.clientId
        }
        // 登录用户信息
        const token = Cookies.get('Authorization');
        if (token) {
            config.headers.Authorization = token.startsWith('Bearer ')? token : `Bearer ${token}`
        }
        // 记录来源页面
        config.headers.RefererPage = window.location.href;
        //语言配置
        if (localConfigStore.language) {
            config.headers.Language = localConfigStore.language;
        }
        //三方登录ID
        const openId = Cookies.get('Open-Id');
        if (openId) {
            config.headers['Open-Id'] = openId;
        }
        config.paramsSerializer = function (params) {
            params = JSON.parse(JSON.stringify(params));
            params['json'] = 1;
            return jquery.param(params);
        };

        //数据传输加密
        let api_encryption = 0;
        if(configStore.config.api_encryption && //允许加密提交
            rsa.server_rsa_pub && //有服务端公钥
            config.method!='get' && //非get请求
            !configStore.config.debug //调试模式不加密
        ){ //判断是否可使用加密传输
            config.headers['Api-Encryption'] = api_encryption = 1;
            let data = config.data;
            if (typeof data === 'object') {
                let app_key = configStore.config.app_key || rsa.app_key;
                let encrypt_data = encryptData(JSON.stringify(config.data),rsa.server_rsa_pub,app_key);
                config.data = encrypt_data;
            }
        }
        if(configStore.config.api_encryption && //允许加密响应
            rsa.client_rsa && //
            !configStore.config.debug
        ){//是否支持响应加密
            config.headers['Support-Response-Encryption'] = 1;
        }

        return config
    },
    (error) => {
        // 请求错误处理
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
      response = decryptResponse(response);
      return response
  },
  (error) => {
      let response = error.response;
      error.response = decryptResponse(response);
    return Promise.reject(error)
  }
)

// 导出配置好的axios实例
export default request
